﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using NHibernate;
using NHibernate.Criterion;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Data;
using Rodunu.Movies.Interfaces.Movie;
using Rodunu.Movies.Interfaces.Services;

namespace Rodunu.Movies.Logic.Movie
{
    public class ServicesLogic : Repository<Services>, IServices
    {
        public IList<Contracts.Services> FindAvailableServices()
        {
            return
                DBHelper.GetCurrentSession().CreateCriteria(typeof(Contracts.Services))
                .Add(Restrictions.Eq("Enabled", true))
                .List<Contracts.Services>();
        }

        public static string Parse(HttpWebResponse response)
        {
            if (response == null)
                return null;
            string decodedBody;

            NameValueCollection bodyParams = new NameValueCollection();

            using (MemoryStream ms = new MemoryStream())
            {
                System.IO.Stream stream = response.GetResponseStream();
                byte[] buffer = new byte[32768];

                int read;

                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }

                Encoding bodyEncoding = Encoding.ASCII;
                if (!String.IsNullOrEmpty(response.ContentEncoding))
                    bodyEncoding = Encoding.GetEncoding(response.ContentEncoding);

                decodedBody = HttpUtility.UrlDecode(ms.ToArray(), bodyEncoding);

                string[] nameValuePairs = decodedBody.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string nameValuePair in nameValuePairs)
                {
                    string[] nameValuePairParts = nameValuePair.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    if (nameValuePairParts.Length == 2)
                        bodyParams.Add(nameValuePairParts[0], nameValuePairParts[1]);
                }
            }

            return decodedBody;
        }
    }
}
